import axios from "axios";
//import router from "../router";
 import Router from "vue-router";

 const instance = axios.create({
  // 调用的api地址
  baseURL: "https://localhost:7145/",
  timeout: 50000,
});

//添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // if (localStorage.getItem('authorizationpms')!=null) {
    //   config.headers.Authorization = localStorage.getItem('authorizationpms');
    // }
    
    // 在发送请求之前做些什么
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response;
  },
  function (error) {
    // 接口调用失败
    let r = null;
    if (error && error.response) {
      let msg = "";
      switch (error.response.data.code) {
        case 400:
          msg = "错误请求";
          break;
        case 401:
          localStorage.removeItem("authorizationpms");
          msg = "未授权，请重新登录";
          r = "/";
          break;
        case 403:
          msg = "拒绝访问";
          break;
        case 404:
          msg = "请求错误,未找到该资源";
          // window.location.href = "/NotFound"
          break;
        case 405:
          msg = "请求方法未允许";
          break;
        case 408:
          msg = "请求超时";
          break;
        case 500:
          if (error.response.data.message !== null) {
            msg = error.response.data.message;
          } else msg = "服务器出错!";
          break;
        case 501:
          msg = "服务器无法识别请求方法";
          break;
        case 502:
          msg = "网络错误";
          break;
        case 503:
          msg = "服务不可用";
          break;
        case 504:
          msg = "网络超时";
          break;
        case 505:
          msg = "http版本不支持该请求";
          break;
        default:
          msg = "未知的错误，请联系管理员！";
      }
      // 在某些特定情况下跳转页面
      if (r !== null) {
        Router.push("/");
      }
      this.$Message.error({ message: msg });
    }
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

//导出对象/实例
export default instance;
